import {PlusOutlined, EditOutlined, EyeOutlined, DeleteOutlined} from '@ant-design/icons';
import {Button, message, Modal, Space} from 'antd';
import React, {useRef, useState} from 'react';
import {PageContainer} from '@ant-design/pro-layout';
import type {ActionType, ProColumns} from '@ant-design/pro-table';
import ProTable from '@ant-design/pro-table';
import VehicleForm from './components/VehicleForm';
import VehicleDetail from './components/VehicleDetail';
import {
  addVehicleAPI,
  deleteVehicleAPI,
  pageVehicleAPI,
  updateVehicleAPI
} from "@/pages/vehicle/vehicle-manager/service";

const VehicleManager: React.FC = () => {
  const actionRef = useRef<ActionType>();
  const [modalVisible, setModalVisible] = useState(false);
  const [currentVehicle, setCurrentVehicle] = useState<API.IVehicle | undefined>(undefined);
  const [detailVisible, setDetailVisible] = useState(false);

  const columns: ProColumns<API.IVehicle>[] = [
    {
      title: '车牌号码',
      dataIndex: 'plateNumber',
      width: 120,
    },
    {
      title: '车辆类型',
      dataIndex: 'vehicleType',
      valueEnum: {
        '1': {text: '小型汽车'},
        '2': {text: '中型客车'},
        '3': {text: '大型货车'},
      },
      width: 100,
    },
    {
      title: '品牌型号',
      render: (_, record) => `${record.brand} ${record.model}`,
      width: 150,
      hideInSearch: true,
    },
    {
      title: '颜色',
      dataIndex: 'color',
      width: 80,
      hideInSearch: true,
    },
    {
      title: '变速箱',
      dataIndex: 'transmissionType',
      valueEnum: {
        '1': {text: '手动'},
        '2': {text: '自动'},
      },
      width: 80,
    },
    {
      title: '状态',
      dataIndex: 'status',
      valueEnum: {
        1: {text: '可用', status: 'Success'},
        2: {text: '维修中', status: 'Warning'},
        3: {text: '已报废', status: 'Error'},
        4: {text: '已出售', status: 'Default'},
      },
      width: 100,
    },
    {
      title: '操作',
      valueType: 'option',
      width: 180,
      render: (_, record) => [
        <a
          key="view"
          onClick={() => {
            setCurrentVehicle(record);
            setDetailVisible(true);
          }}
        >
          <EyeOutlined/> 查看
        </a>,
        <VehicleForm
          key="edit"
          trigger={<a><EditOutlined/> 编辑</a>}
          initialValues={record}
          title={`编辑车辆 - ${record.plateNumber}`}
          onFinish={async (values) => {
            const {data} = await updateVehicleAPI({...values, id: record.id, version: record.version})
            if (data) {
              actionRef.current?.reload()
              message.success('修改成功')
            }
            return data
          }}
        />,
        <a style={{color: 'red'}}
           key="delete"
           onClick={async () => {
             Modal.confirm({
               title: '确认删除',
               content: `确定要删除车牌号为 ${record.plateNumber} 的车辆吗？`,
               onOk: async () => {
                 const {data} = await deleteVehicleAPI(record?.id || '')
                 if (data) {
                   message.success('删除成功');
                   actionRef.current?.reload();
                 }
               },
             });
           }}
        >
          <DeleteOutlined/> 删除
        </a>,
      ],
    },
  ];


  return (
    <div style={{minHeight: '80vh'}}>
      <ProTable<API.IVehicle>
        columns={columns}
        actionRef={actionRef}
        request={async (params) => {
          const {data} = await pageVehicleAPI(params)
          return data
        }}
        size={'small'}
        rowKey="id"
        search={{
          labelWidth: 'auto',
          span: 6,
        }}
        toolBarRender={() => [
          <VehicleForm
            key="create"
            trigger={
              <Button type="primary">
                <PlusOutlined/> 新增车辆
              </Button>
            }
            title="新增车辆"
            onFinish={async (values) => {
              const {data} = await addVehicleAPI(values)
              if (data) {
                message.success('新增成功');
                actionRef.current?.reload();
              }
              return data
            }}
          />,
        ]}
      />
      <Modal
        title="车辆详情"
        width={800}
        open={detailVisible}
        onCancel={() => setDetailVisible(false)}
        footer={null}
      >
        <VehicleDetail data={currentVehicle || {}}/>
      </Modal>
    </div>
  );
};

export default VehicleManager;
